package com.isyscore.os.metadata.kettle.vis;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeGroupType;
import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import com.isyscore.os.metadata.enums.KettleFilterFunction;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 数据过滤
 */
@ApiModel("数据过滤组件")
@Data
@EqualsAndHashCode(callSuper = false)
public class FilterRowsNode extends VisNode {
    @ApiModelProperty("符合条件的输出节点")
//    @NotBlank(message = "符合条件的输出节点不能为空")
    private String sendTrueTo;
    @ApiModelProperty("不符合条件的输出节点")
//    @NotBlank(message = "不符合条件的输出节点不能为空")
    private String sendFalseTo;
    @ApiModelProperty("条件")
    @NotEmpty(message = "条件不能为空")
    @Valid
    private List<FilterCondition> conditions;


    @Override
    public void valueOf(Map<String, Object> params) {
        JSONObject jsonObject = new JSONObject(params);
        this.sendTrueTo = jsonObject.getString("sendTrueTo");
        this.sendFalseTo = jsonObject.getString("sendFalseTo");
        this.conditions = Optional.ofNullable(jsonObject.getJSONArray("conditions")).orElse(new JSONArray()).stream().map(o ->
                JSON.parseObject(JSON.toJSONString(o), FilterCondition.class)).collect(Collectors.toList());
        setId(jsonObject.getString("id"));
        setNodeName(jsonObject.getString("nodeName"));
    }

    @Override
    public String validate() {
        String va= super.validate();
        if(StrUtil.isBlank(va)){
            for(FilterCondition filterCondition:conditions){
                if(KettleFilterFunction.not_null!=filterCondition.getFunction()&&StrUtil.isBlank(filterCondition.getValue())){
                    return "值不能为空";
                }
            }
        }
        return va;
    }

    @Override
    public KettleDataFlowNodeGroupType getGroupType() {
        return KettleDataFlowNodeGroupType.TRANS;
    }
    @Override
    public KettleDataFlowNodeType getNodeType(){
        return KettleDataFlowNodeType.FilterRows;
    }

    @Override
    public boolean isMultiOut() {
        return true;
    }
}
